package tool;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;
import java.util.Stack;

/**
 * @Description:
 * @Author: yjj
 * @Date: 2025/8/28 15:45
 */
public class Main7 {
    public static void main(String[] args) {
        String jsonStr = "{\"code\":0,\"data\":{\"backup\":{\"urlParams\":{\"backup_id\":\"fae19e35-c53e-42ee-8a96-ccd6afe30ed8\"},\"diskUsage\":23,\"id\":\"fae19e35-c53e-42ee-8a96-ccd6afe30ed8\",\"uuid\":\"fae19e35-c53e-42ee-8a96-ccd6afe30ed8\",\"status\":\"available\"}},\"requestId\":\"7baa5b25-03e0-4b06-b08c-7ef37fa40a63\"}";
        System.out.println(getValueByKeyStr(jsonStr, "backup_id"));
    }

    public static String getValueByKeyStr(String jsonStr, String keyStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Stack<Object> stack = new Stack<>();
        stack.push(jsonObject); // 将根对象压入栈中
        String retrunStr = null;
        while (!stack.isEmpty()) {
            Object current = stack.pop(); // 弹出栈顶元素
            if (current instanceof JSONObject) {
                // 如果是 JSONObject，获取所有键值对并压入栈中
                JSONObject obj = (JSONObject) current;
                for (Map.Entry<String, Object> entry : obj.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    if (key.equals(keyStr)) {
                        retrunStr = value.toString();
                        return retrunStr;
                    }
                    // 如果值是 JSONObject 或 JSONArray，压入栈中
                    if (value instanceof JSONObject || value instanceof JSONArray) {
                        stack.push(value);
                    }
                }
            } else if (current instanceof JSONArray) {
                // 如果是 JSONArray，遍历数组中的每个元素并压入栈中
                JSONArray array = (JSONArray) current;
                for (Object item : array) {
                    // 如果元素是 JSONObject 或 JSONArray，压入栈中
                    if (item instanceof JSONObject || item instanceof JSONArray) {
                        stack.push(item);
                    }
                }
            }
        }
        return retrunStr;
    }
}
